package com.liujinghe.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liujinghe.pojo.Music;
import com.liujinghe.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("music")
public class MusicController {

    @Autowired
    private MusicService musicService;

    @RequestMapping("findAll")
    public List<Music> findAll(){
        return musicService.findAll();
    }

    @RequestMapping("findByPage")
    public Map<String,Object> findByPage(
            @RequestParam(value = "page",required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(value = "limit",required = false,defaultValue = "2") Integer pageSize
    ){

        PageHelper.startPage(pageNum,pageSize);
        List<Music> musicList = musicService.findAll();

        PageInfo<Music> musicPageInfo = new PageInfo<>(musicList);

        HashMap<String, Object> map = new HashMap<>();
        map.put("data",musicPageInfo.getList());//分页数据
        map.put("code",0);//成功返回的code值为：0
        map.put("msg","分页信息");//code值不为0，显示msg中的内容
        map.put("count",musicPageInfo.getTotal());//总记录数

        return map;
    }


    @RequestMapping("upload")
    public Map<String,Object> upload(MultipartFile file, Model model){//MultipartFile的变量名和type=file表单中name属性的属性值一致
        System.out.println("upload...");
        //获取文件名
        String uploadFileName = file.getOriginalFilename();
        System.out.println("原始的文件名："+uploadFileName);
        //UUID保证文件名的唯一性
        uploadFileName = UUID.randomUUID().toString().replace("-","")+uploadFileName;
        System.out.println("现在的文件名："+uploadFileName);
        //上传路径
        String uploadPath = "D:\\tomcat-server\\apache-tomcat-8.5.31\\webapps\\upload\\";
        //上传
        try {
            file.transferTo(new File(uploadPath,uploadFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("code",0);//分页数据

        return map;
    }
}
